package com.example.springcloud.controller;

import com.example.springcloud.entity.Payment;
import com.example.springcloud.utils.Constant;
import com.example.springcloud.utils.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * The type Order controller.
 */
@RestController
@RequestMapping(value = "/consumer")
@Slf4j
public class OrderController {

    private static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE/spring-cloud";
    @Resource // 注入 RestTemplate
    private RestTemplate restTemplate; // 需要用这个工具在 80 端口访问 8001 端口

    /**
     * Create payment result entity.
     *
     * @param payment the payment
     * @return the result entity
     */
    @PostMapping(value = "/payment/create")
    public ResultEntity createPayment(@RequestBody Payment payment) {

        // 从80调8001 注意地址拼接方式
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, ResultEntity.class);

    }

    @GetMapping(value = "/payment/testZipkin")
    public String testZipkin() {

        return restTemplate.getForObject(PAYMENT_URL + "/payment/zipkin", String.class);

    }

    /**
     * Gets payment.
     *
     * @param id the id
     * @return the payment
     */
    @GetMapping(value = "/payment/get/{id}")
    public ResultEntity getPayment(@PathVariable(value = "id") Long id) {

        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, ResultEntity.class);
    }

    @GetMapping(value = "/payment/getEntity/{id}")
    public ResultEntity getResultEntity(@PathVariable("id") Long id) {

        ResponseEntity<ResultEntity> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, ResultEntity.class);
        if (entity.getStatusCode().is2xxSuccessful()) {
            return entity.getBody();
        } else {
            return new ResultEntity<>(Constant.RESPONSE_CODE_500);
        }
    }

}
